<template>
  <el-table :data="stockTransfers" border style="width: 100%">
    <el-table-column prop="transfer_no" label="调拨单号" />
    <el-table-column prop="from_warehouse" label="调出仓库" />
    <el-table-column prop="to_warehouse" label="调入仓库" />
    <el-table-column prop="status" label="状态">
      <template #default="{ row }">
        {{ statusMap[row.status] }}
      </template>
    </el-table-column>
    <el-table-column prop="create_user.name" label="创建人" />
    <el-table-column prop="create_time" label="创建时间" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button size="small" @click="viewDetail(row)">详情</el-button>
        <el-button size="small" type="danger" v-if="row.status === 0" @click="deleteStockTransfer(row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="queryParams.page"
    v-model:page-size="queryParams.size"
    :total="total"
    @current-change="getList"
    layout="prev, pager, next"
    style="margin-top: 20px;"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const stockTransfers = ref([])
const total = ref(0)
const queryParams = ref({
  page: 1,
  size: 10,
  transfer_no: '',
  from_warehouse: '',
  to_warehouse: '',
  status: null,
  start_time: '',
  end_time: ''
})

const statusMap = {
  0: '待审核',
  1: '已审核',
  2: '已取消'
}

const getList = async () => {
  try {
    const res = await request.get('/api/stock-transfer/', { params: queryParams.value })
    stockTransfers.value = res.records
    total.value = res.total
  } catch (error) {
    console.error('获取调拨单列表失败:', error)
  }
}

const viewDetail = (row) => {
  // 跳转到详情页面
  router.push(`/stock-transfer/detail/${row.id}`)
}

const deleteStockTransfer = async (id) => {
  try {
    await request.delete(`/api/stock-transfer/${id}/`)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  getList()
})
</script>
